package com.movitech.mobile.cz.base.purchase.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizvo.MyFormRequestVO;
import com.movitech.mobile.cz.base.purchase.entity.WFlowForm;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowForm;
import com.movitech.mobile.cz.base.purchase.entity.ext.WFowFormListReq;
import com.movitech.mobile.cz.base.purchase.mapper.WFlowFormMapper;
import com.movitech.mobile.cz.base.purchase.mapper.ext.ExtWFlowFormMapper;
import com.movitech.mobile.cz.base.purchase.service.WFlowFormService;
import com.movitech.mobile.cz.base.purchase.service.WFlowFormSupplierEntryService;
import com.movitech.mobile.cz.base.supplier.entity.SHistoryComment;
import com.movitech.mobile.cz.base.supplier.entity.SMyDeals;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliers;
import com.movitech.mobile.cz.base.supplier.entity.ext.BidNodeDetail;
import com.movitech.mobile.cz.base.supplier.entity.ext.SHistoryCommentResponseVO;
import com.movitech.mobile.cz.base.supplier.entity.ext.SMyDealsResponseVO;
import com.movitech.mobile.cz.base.supplier.service.SHistoryCommentService;
import com.movitech.mobile.cz.base.supplier.service.SMyDealsService;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 流程表单主表 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-15
 */
@Service
public class WFlowFormServiceImpl extends ServiceImpl<WFlowFormMapper, WFlowForm> implements WFlowFormService {

    @Autowired
    private ExtWFlowFormMapper extWFlowFormMapper;
    @Autowired
    private WFlowFormMapper wFlowFormMapper;

    @Autowired
    private SSuppliersService sSuppliersService;

    @Autowired
    private SHistoryCommentService sHistoryCommentService;

    @Autowired
    private SMyDealsService sMyDealsService;

    @Autowired
    private SAttachmentService sAttachmentService;

    @Autowired
    private WFlowFormSupplierEntryService wFlowFormSupplierEntryService;

    @Override
    public ExtWFlowForm getBiddingDocumentBaseInfoByFlowFormId(String flowFormId) {
        return extWFlowFormMapper.getBiddingDocumentBaseInfoByFlowFormId(flowFormId);
    }

    @Override
    public ExtWFlowForm getExtByFormId(String formId) {
        WFowFormListReq wFlowForm = new WFowFormListReq();
        wFlowForm.setId(formId);
        List<ExtWFlowForm> data = extWFlowFormMapper.selectExtList(wFlowForm);
        return data.get(0);
    }

    @Override
    public boolean saveWFlowForm(WFlowForm wFlowForm) {

        LicenseUtil.INSTANCE.validate();
        if (wFlowForm != null) {
            if (StringUtils.isEmpty(wFlowForm.getId())) {
                wFlowForm.setId(IdGenUtils.uuid());
            }

            Date createDate = new Date();
            String userId = UserUtils.getCurrentUserId();
            wFlowForm.setCreateBy(userId);
            wFlowForm.setCreateDate(createDate);
            wFlowForm.setUpdateBy(userId);
            wFlowForm.setUpdateDate(createDate);
            wFlowForm.setDelFlag(CommonConstants.NO_INTEGER);

            int i = baseMapper.insert(wFlowForm);

            return i > 0;
        }

        return false;
    }

    @Override
    public boolean updateWFlowForm(WFlowForm wFlowForm) {

        LicenseUtil.INSTANCE.validate();
        if (wFlowForm != null && StringUtils.isNotEmpty(wFlowForm.getId())) {

            Date updateDate = new Date();
            String userId = UserUtils.getCurrentUserId();
            wFlowForm.setUpdateBy(userId);
            wFlowForm.setUpdateDate(updateDate);

            int i = baseMapper.updateById(wFlowForm);

            return i > 0;

        }

        return false;
    }

    @Override
    public RestReturnResult<Object> getMyFormList(HttpServletRequest request, HttpServletResponse response, MyFormRequestVO myFormRequestVO) {
        RestReturnResult returnResult = RestReturnResult.error();
        LicenseUtil.INSTANCE.validate();
        String userId = UserUtils.getOuterCurrentUserId();
        if (StringUtils.isEmpty(userId)) {
            return returnResult;
        }
        //根据用户id查询供方id
        EntityWrapper entityWrapper = new EntityWrapper();
        SSuppliers sSuppliers = new SSuppliers();
        sSuppliers.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        sSuppliers.setSysUserId(userId);
        entityWrapper.setEntity(sSuppliers);
        sSuppliers = sSuppliersService.selectOne(entityWrapper);
        if (sSuppliers == null) {
            return RestReturnResult.success();
        }
        if (myFormRequestVO.getPageFlag() != null && myFormRequestVO.getPageFlag() == 0) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("formName", myFormRequestVO.getFormName());
            map.put("supplierId", sSuppliers.getId());
            map.put("pageFlag", myFormRequestVO.getPageFlag());
            map.put("orderBy", " wff.update_date desc ");
            List<ExtWFlowFormMapper> ls = extWFlowFormMapper.getMyFormList(map);
            returnResult = new RestReturnResult(CommonConstants.SUCCESS, ls);
        } else {
            PageCode pageCode = new PageCode(myFormRequestVO.getPageNumber(), myFormRequestVO.getPageSize());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("formName", myFormRequestVO.getFormName());
            map.put("supplierId", sSuppliers.getId());
            map.put("pageFlag", myFormRequestVO.getPageFlag());
            map.put("orderBy", " wff.update_date desc ");
            pageCode.setCount(extWFlowFormMapper.getMyFormListCount(map));

            map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            List<ExtWFlowFormMapper> ls = extWFlowFormMapper.getMyFormList(map);
            pageCode.setList(ls);
            returnResult = new RestReturnResult(CommonConstants.SUCCESS, pageCode);
        }
        return returnResult;
    }

    @Override
    public void clearContractById(String formId) {
        LicenseUtil.INSTANCE.validate();
		wFlowFormMapper.clearContractById(formId);
    }

    @Override
    public RestReturnResult<Object> getBidNodeDetail(String formId) {
        LicenseUtil.INSTANCE.validate();
        RestReturnResult restReturnResult = RestReturnResult.success();
        BidNodeDetail bidNodeDetail = new BidNodeDetail();
        try {
            EntityWrapper entityWrapper = new EntityWrapper();
            SHistoryComment sHistoryComment = new SHistoryComment();
            sHistoryComment.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
            sHistoryComment.setRelatedId(formId);
            entityWrapper.setEntity(sHistoryComment);
            entityWrapper.orderBy(" update_date ", false);
            List<SHistoryComment> ls = sHistoryCommentService.selectList(entityWrapper);

            //流程步骤
            if (ls != null && ls.size() > 0) {
                List<SHistoryCommentResponseVO> SHistoryCommentResponseVOList = ListObjCopyUtil.copyTo(ls, SHistoryCommentResponseVO.class);
                bidNodeDetail.setLstSHistoryCommentResponseVO(SHistoryCommentResponseVOList);
            }

            //查询最新一条待办
            EntityWrapper wrapper = new EntityWrapper();
            wrapper.last(" limit 1");
//			wrapper.in(" action_type ", MyDealActionTypeEnum.CALIBRATION.getCode()+","+MyDealActionTypeEnum.SEND_BID.getCode());
            wrapper.orderBy(" update_date ", false);
            wrapper.where("del_flag=" + CommonConstants.DEL_FLAG_NORMAL).where("related_id=" + formId);
            SMyDeals sMyDeals = sMyDealsService.selectOne(wrapper);
            if (sMyDeals != null) {
                SMyDealsResponseVO sMyDealsResponseVO = new SMyDealsResponseVO();
                BeanUtils.copyProperties(sMyDeals, sMyDealsResponseVO);
                bidNodeDetail.setSMyDealsResponseVO(sMyDealsResponseVO);
            }

            restReturnResult.setData(bidNodeDetail);
        } catch (Exception e) {
            e.printStackTrace();
            restReturnResult = RestReturnResult.error();
        }
        return restReturnResult;
    }

}
